package servlet;

import bean.AdInfo;
import bean.User;
import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.AdInfoService;
import service.UserService;
import utils.TimeUtil;
import utils.UuidUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static utils.TimeUtil.getTime;

@WebServlet("/AdInfo")
public class AdInfoServlet extends HttpServlet {

    private AdInfoService service = new AdInfoService();
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");// 设置请求参数的编码格式
        response.setContentType("text/html;charset=utf-8");// 设置网页界面相应的代码
        response.setHeader("Access-Control-Allow-Origin", "*");// 允许所有来源访问
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");// 允许指定的请求方法访问
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");// 允许自定义的请求头部

        String type = request.getParameter("type");
        String rtStr = "";

        try {
            // bubble-Homepage 调用
            if ("homepage".equals(type)) {
                rtStr = GetAdsInfo(request, response);
            }

            // Buy-Page 调用
            if ("buy".equals(type)) {
                rtStr = BuyAd(request, response);
            }

            // HotAd-Page 获取热门广告排行
            if ("hot".equals(type)) {
                rtStr = GetHotAdsInfo(request, response);
            }

            // 登出
            if ("logout".equals(type)) {
                rtStr = Logout(request, response);
            }

            // Info-Page 根据用户ID获取用户广告数据
            if ("ads".equals(type)) {
                rtStr = GetAdsInfoById(request, response);
            }

            // Edit-Page 编辑更新广告信息
            if ("edit".equals(type)) {
                rtStr = UpdateAdInfo(request, response);
            }

            // Info-Page 删除广告条目
            if ("del".equals(type)) {
                rtStr = DeleteAdById(request, response);
            }

            // Info-Page 根据广告ID删除广告
            if ("search".equals(type)) {
                rtStr = SearchAdBy2Id(request, response);
            }



        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("---------- AdInfo Servlet Runs -----------");
        System.out.println("请求方式: " + request.getMethod());
        System.out.println("请求内容: " + type);
        System.out.println("返回数据: " + rtStr);

    }

    // 根据广告ID搜索广告
    private String SearchAdBy2Id(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        String user_id = (String) session.getAttribute("user_id");

        String ad_id = request.getParameter("ad_id");

        System.out.println(ad_id+user_id);

        AdInfo adInfo = service.SearchAdBy2Id(ad_id, user_id);

        ArrayList<AdInfo> ads = new ArrayList<>();
        ads.add(adInfo);

        String adStr = JSON.toJSONString(ads);

        response.getWriter().write(adStr);

        return adStr;
    }

    // 根据广告ID删除广告
    private String DeleteAdById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ad_id = request.getParameter("ad_id");
        int rt = service.DeleteAdById(ad_id);

        response.getWriter().write("Delete Success");

        return "Delete Success";
    }

    // 更新广告信息
    private String UpdateAdInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AdInfo adInfo = new AdInfo();
        adInfo.setAd_id(request.getParameter("ad_id"));
        adInfo.setAd_brand_name(request.getParameter("ad_brand_name"));
        adInfo.setAd_website(request.getParameter("ad_website"));
        adInfo.setAd_company_name(request.getParameter("ad_company_name"));
        adInfo.setAd_description(request.getParameter("ad_description"));

        int rt = service.UpdateAdInfo(adInfo.getAd_brand_name(), adInfo.getAd_website(), adInfo.getAd_company_name(), adInfo.getAd_description(), adInfo.getAd_id());

        HttpSession session = request.getSession();
        String user_id = (String) session.getAttribute("user_id");

        User user = userService.getUserInfoById(user_id);

        if ("1".equals(user.getIsManager())) {
            response.sendRedirect(request.getContextPath() + "/Manager-Info-Page.html");
        } else {
            response.sendRedirect(request.getContextPath() + "/User-Info-Page.html");
        }

        return "Update Success";
    }

    // 根据用户ID获取广告信息
    private String GetAdsInfoById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        String user_id = (String) session.getAttribute("user_id");

        List<AdInfo> ads = service.GetAdsInfoById(user_id);
        String adsStr = JSON.toJSONString(ads);

        response.getWriter().write(adsStr);


        return adsStr;
    }

    // 登出
    private String Logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
//        session.removeAttribute("user_id");  // 移除指定session
//        session.removeAttribute("isManager");
        session.invalidate();                     // 移除所有session

        response.sendRedirect(request.getContextPath() + "/UserLoginAndRegisterPage.html");

        return "Logout Success";
    }

    // 获取广告信息
    private String GetAdsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {

        List<AdInfo> ads = service.GetAdsInfo();
        String adsStr = JSON.toJSONString(ads);
        response.getWriter().write(adsStr);

        return adsStr;
    }

    // 获取热门广告信息
    private String GetHotAdsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {

        List<AdInfo> ads = service.GetHotAdsInfo();
        String adsStr = JSON.toJSONString(ads);
        response.getWriter().write(adsStr);

        return adsStr;
    }

    // 上传广告信息
    private String BuyAd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        String user_id = (String) session.getAttribute("user_id");
//        System.out.println("user_id: " + user_id);

        AdInfo ad = new AdInfo();
        ad.setUser_id(user_id);

        //1.确认该操作是否支持文件上传操作，enctype="multipart/form-data"
        if (ServletFileUpload.isMultipartContent(request)) {
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //4.从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);

            //创建一个标记位，标记当前时候有上传文件的操作
            boolean flag = false;
            for (FileItem item : fileItems) {
                if (item.getName() != null) {
                    flag = true;
                    break;
                }
            }
            //如果有，使用uuid给改图片生成一个唯一的地址
            String imgId = UuidUtil.getUuid() + ".png";
            // --处理form表单提交过来的文件数据
            for (FileItem item : fileItems) {
                //5.当前表单是否是文件表单
                if (!item.isFormField()) {
                    //6.从临时存储文件的地方将内容写入到指定位置
                    File upload = new File(this.getServletContext().getRealPath("img/bubble"), imgId);
                    //获取当前图片虚拟路径，如果是存的绝对路径，img的src获取不到
//                    String imgPath = request.getContextPath() + "/img/bubble/" + imgId;

                    String imgPath = "img/bubble/" + imgId;
                    item.write(upload);

                    ServletContext context = request.getServletContext();
                    //存到application域中
                    context.setAttribute("imgPath", imgPath);

                    ad.setAd_img(imgPath);
                }

                String name = item.getFieldName();
                if ("ad_brand_name".equals(name)) {
                    String value = item.getString("utf-8");
                    ad.setAd_brand_name(value);
                } else if ("ad_website".equals(name)) {
                    String value = item.getString("utf-8");
                    ad.setAd_website(value);
                } else if ("ad_company_name".equals(name)) {
                    String value = item.getString("utf-8");
                    ad.setAd_company_name(value);
                } else if ("ad_description".equals(name)) {
                    String value = item.getString("utf-8");
                    ad.setAd_description(value);
                } else if ("ad_status".equals(name)) {
                    String value = item.getString("utf-8");
                    ad.setAd_status(value);
                } else if ("ad_size".equals(name)) {
                    String value = item.getString("utf-8");
                    ad.setAd_size(value);
                }
            }
        }

        long timeNow = System.currentTimeMillis();
        String time = getTime(timeNow);

        ad.setAd_hot("0");
        ad.setAd_date(time);

        int rt = service.BuyAd(ad.getAd_brand_name(), ad.getAd_website(), ad.getAd_company_name(),
                ad.getAd_description(), ad.getAd_status(), ad.getAd_size(), ad.getAd_img(), ad.getUser_id(), "0", time);

        User user = userService.getUserInfoById(user_id);

        if ("1".equals(user.getIsManager())) {
            response.sendRedirect(request.getContextPath() + "/Manager-bubble-Homepage.html");
        } else {
            response.sendRedirect(request.getContextPath() + "/User-bubble-Homepage.html");
        }

        int i = userService.userMoneyCost(user_id, ad.getAd_size()); //ad_size即消费的金额

        return "" + rt + " " + i;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
